# -*- coding: utf-8 -*-
# @Time : 2022/3/21 9:23
# @Author : Administrator
# @Email : simple_days@qq.com
# @File : user.py
# @Project : flaskProject
# ©Copyright : 中国电建集团透平科技有限公司版权所有
import json

from flask import jsonify

from flask_restful import Resource, Api, reqparse, abort
from loguru import logger
from common.MongoUtil import MongoUtil
from common.MongoUtil import objectIDtoStr

mongoUtil = MongoUtil(uri='mongodb://172.2.6.93:30002', db_name='pcttTest', coll_name='user')
logger.info(f'获取到mongod数据库{mongoUtil}')


parser = reqparse.RequestParser()
parser.add_argument('username')
parser.add_argument('status')
parser.add_argument('date')



# userList
# shows a list of all users, and lets you POST to add new tasks
class UserList(Resource):
    def get(self):
        parser.add_argument('group')
        args = parser.parse_args()
        if args['group']:
            userlist = mongoUtil.collection.find({'工作组':args['group']}, {'_id': 0})
            return jsonify(list(userlist))
        logger.info(args)
        userlist = mongoUtil.collection.find({}, {'_id': 0})
        return jsonify(list(userlist))

    def post(self):
        # parser = reqparse.RequestParser()
        parser.add_argument('id', type=int, required=True, help="必须输入用户ID")
        args = parser.parse_args()
        user = {'username': args['username'], 'status': args['status'], 'date': args['date'],'id':args['id']}
        x = mongoUtil.collection.insert_one(user)
        logger.info(f'{user}成功插入，插入id：{x.inserted_id}')
        return objectIDtoStr(user), 201


class User(Resource):
    def get(self, id):
        # user = mongoUtil.collection.find_one({'id': user_id}, {'_id': 0})
        uid = int(id)
        user_coll = mongoUtil.database['user']
        user = user_coll.find_one({'id': uid}, {'_id': 0})
        logger.info(f'通过{id}查询到用户{user},mongo表{mongoUtil.collection}')
        return jsonify(user)

    def delete(self, id):
        result = mongoUtil.collection.delete_one({'id': int(id)})
        if result.deleted_count > 0:
            logger.info(f'删除用户的：{id}，{result}')
            return {'result':'ok','count':result.deleted_count}, 204
        else:
            return '', 404

    def put(self, asset_id):
        args = parser.parse_args()
        task = {'task': args['task']}
        [asset_id] = task
        return task, 201
